import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import viteCompression from 'vite-plugin-compression'
import dtsPlugin from 'vite-plugin-dts'
import * as path from 'node:path';
import packages from './package.json' with { type: 'json' };
export default defineConfig((configEnv)=>{
  const isModule = configEnv.mode  === 'module' || configEnv.mode  === 'module-jsx';
  const isJsx = configEnv.mode  === 'module-jsx' || configEnv.mode  === 'production-jsx';
  const entry = isJsx?resolve(__dirname, './src/indexWithJsx.ts'):resolve(__dirname, './src/index.ts');
  return {
    resolve:{
      alias:{
        'chalk': path.resolve(__dirname, 'build/noopChalk.js'),
        'debug$': path.resolve(__dirname, 'build/noopDebug.js'),
      }
    },
    plugins: [
      dtsPlugin({
        outDir:"dist/types",
        rollupTypes: true
      }),
      visualizer({
        filename: `dist/stats${isModule?'-module':''}${isJsx?'-jsx':''}.html`
      }),
      nodePolyfills({
        include: [
          'path','fs','process',
          // ...(isJsx?['module','assert']:[])
        ],
        globals: {
          Buffer: true,
          global: true,
          process: true
        },
        overrides: {},
        protocolImports: true,
      }),
      ...!isModule?[
        viteCompression({
          algorithm: "gzip", // 使用 gzip 压缩
          threshold: 1024000 // 对大于 1mb 的文件进行压缩
        }),
        viteCompression({
          algorithm: "brotliCompress", // 使用 gzip 压缩
          threshold: 1024000 // 对大于 1mb 的文件进行压缩
        })
      ]:[]
    ],
    optimizeDeps:{

    },
    build: {
      target: isModule ? "modules" :"es2015",
      emptyOutDir: false,
      outDir: isModule?'dist/es':'dist/umd',
      // sourcemap: !isModule,
      lib: {
        entry: entry,
        name: 'Vue3SfcRender',
        // 将添加适当的扩展名后缀
        fileName: (format) => 'vue3-sfc-loader'+(isJsx?'-jsx':'')+(isModule?".mjs":".umd.js"),
        formats: [isModule?'es':'umd'],
      },
      rollupOptions: {
        external: isModule? Object.keys(packages.dependencies): [],
      },
    },
  }
})
